<!DOCTYPE html>
<html>
<head>
<!-- Image Capture Browser Test -->
<script type="text/javascript" src="webrtc_test_utilities.js"></script>
<script>
const NUM_PHOTOS_TO_TAKE = 10;
var track;
var imageCapture;
var count = 0;

function takePhoto(imageCapture) {
  console.log("Calling takePhoto");
  return imageCapture.takePhoto()
    .then(blob => {
      count = count+1;
      console.log("TakePhoto succeeded " + count + " times.");
      return closeCamera();
    })
    .catch(error => {
      console.log("takePhoto failed with " + error)
      throw new Error("takePhoto failed with " + error);
    });
}

async function openCamera() {
  try {
    const mediaStream = await navigator.mediaDevices.getUserMedia({video: true});
    document.getElementById('local-view').srcObject = mediaStream;

    track = mediaStream.getVideoTracks()[0];
    track.onmute = function(evt) {
      console.log("Track is now muted");
    }
    track.onunmute = function(evt) {
      console.log("Track is now unmuted");
    }
    imageCapture = new ImageCapture(track);
    if (track.readyState != 'live') {
      console.log('readyState = ' + track.readyState);
    }
    if (track.muted) {
      console.log("Track is currently muted. Waiting with takePhoto call.");
      await new Promise(resolve => {
        track.onunmute = function(evt) {
          resolve();
        };
      });
      console.log("Track is now unmuted");
    }
    return takePhoto(imageCapture);
  } catch(error) {
    console.log("getUserMedia failed with " + error)
    throw new Error("getUserMedia failed with " + error);
  }
}

function closeCamera() {
  document.querySelector('video').srcObject = null;
  track.onmute = null;
  track.onunmute = null;
  track = null;
  imageCapture = null;

  if (count < NUM_PHOTOS_TO_TAKE) {
    return new Promise(resolve => setTimeout(resolve, 0))
      .then(openCamera);
  } else {
    return logSuccess();
  }
}

function testTake10PhotosSucceeds() {
  return openCamera();
}
</script>
</head>
<body>
  <video id="local-view" autoplay></video>
</body>
</html>
